﻿using System;
using System.Data;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using ProjectManApi.Extensions;
using Microsoft.AspNetCore.Authorization;
using Nacos.AspNetCore;
using learun.util;
using BusinessRule;
using NLog;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Net;
using System.Text;
using System.IO;
using System.Dynamic;
using Microsoft.AspNetCore.Mvc.Rendering;
using Newtonsoft.Json.Linq;
using BusinessEntity.CGManage;
using BusinessEntity;

namespace ProjectManApi.Controllers.CGGL
{
    public class CGManageController : MvcControllerBase
    {
        #region "测试"

        private readonly INacosServerManager _serverManager;
        public CGManageController(INacosServerManager serverManager) : base(serverManager)
        {
            _serverManager = serverManager;
        }
        #endregion

        #region"采购计划"
        /// <summary>
        /// 列表页面
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>

        [HttpGet]
        // [AllowAnonymous]
        public async Task<IActionResult> GetCG_Project([FromQuery] CG_ProjectQuerry entity)
        {
            try
            {
                _logger.Log(LogLevel.Info, this.Url.Action() + this.Request.QueryString.Value);
                entity.UserID = GetUserId();
                entity.DepartID = await GetDepId("purchase_permission");
                (IEnumerable<dynamic>, int) SelectTable = await BusinessRule.Purchase.CGGL_CG.GetCG_Project(entity);
                List<string> list = new List<string>();
                foreach (dynamic item in SelectTable.Item1)
                {
                    string id = item.jhcgbm;
                    list.Add(id);
                }

                List<JavaApi.SPSDataItem> spitems = await JavaApi.GetSPStatusJavaAPI(entity.FormCode, GetUserAccount(), list, await GetICApiInfo());
                foreach (dynamic item in SelectTable.Item1)
                {
                    string id = item.jhcgbm;
                    var spstatus = spitems.Where(ii => ii.businessId == id).FirstOrDefault();
                    string status = "unknown";
                    if (item.zt == "1")
                    {
                        status = "draft";

                    }
                    else if (item.zt == "2")
                    {
                        status = "uncheck";

                    }
                    else if (item.zt == "9")
                    {
                        status = "checking";

                    }
                    else if (item.zt == "3")
                    {
                        status = "checked";

                    }
                    else if (item.zt == "4")
                    {
                        status = "reject";

                    }
                    else if (item.zt == "5")
                    {
                        status = "invalid";

                    }
                  
                    else
                    {
                        status = "unfilled";
                    }
                    item.panguData = GetPanGudData(spstatus, status);
                }

                Page pa = new Page();
                pa.records = SelectTable.Item1;
                pa.total = SelectTable.Item2;
                _logger.Log(LogLevel.Info, Success(pa).ToJson());
                return Success(pa);
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Info, ex.Message);
                return Fail(ex.Message);
            }
        }
        /// <summary>
        /// 获取详情
        /// </summary>
        /// <param name="jhcgbm"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetCG_Project_Detail(string jhcgbm)
        {
            try
            {
                DataTable SelectTable = await BusinessRule.Purchase.CGGL_CG.GetCG_Project_Detail(jhcgbm);
                return Success(SelectTable);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }

        }

        //存草稿、提交

        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> SubmitCG_Project([FromBody] CG_Project cg)
        {

            try
            {
                if(cg.cgjh.zt==""|| cg.cgjh.zt == null)
                    {
                    return Fail("数据状态错误");
                    }
                if (cg.cgjh.bmdm == "" || cg.cgjh.bmdm == null)
                {
                    return Fail("数据权限缺失");
                }
                if (cg.cgjh.jhcgbm == "" || cg.cgjh.jhcgbm == null)
                {
                    cg.cgjh.jhcgbm = await JavaApi.BusinessBMJavaAPI("purchase_project", "采购计划", await GetICApiInfo());
                    cg.cgjh.listid = "1";
                }
                if (cg.cgjh.jhcgbm == null)
                {
                    return Fail("采购编码获取失败");
                }
                if (cg.cgjh.zt == "1")
                {
                    if (await JavaApi.UploadFileJavaAPI(cg.cgjh.jhcgbm, cg.File, await GetICApiInfo()))
                    {

                        await BusinessRule.Purchase.CGGL_CG.InsertCG_Project(cg.cgjh);

                    }
                    else
                    {
                        await BusinessRule.Purchase.CGGL_CG.InsertCG_Project(cg.cgjh);

                    }
                    return Success("成功");
                }
                else
                {
                   
                    if (await JavaApi.UploadFileJavaAPI(cg.cgjh.jhcgbm, cg.File, await GetICApiInfo()))
                    {
                        CG_Submit submit = new CG_Submit();
                        submit.submitid = cg.cgjh.jhcgbm;
                        submit.submitmc = cg.cgjh.jhcgmc;
                        submit.submitje = cg.cgjh.ysje.ToString();
                        submit.submitlx = "采购计划";
                        bool bsp = false;
                        JavaApi.SPLEnt spl = new JavaApi.SPLEnt();
                        spl.businessName = "采购计划";
                        spl.businessId = cg.cgjh.jhcgbm;
                        // spl.publicParamKey = "FEE_PROCESS";
                        spl.formCode = cg.File.code;

                        //spl.description = Newtonsoft.Json.JsonConvert.SerializeObject(htsmbmit);
                        JavaApi.SPLEnt.Auditdescription _description = new JavaApi.SPLEnt.Auditdescription() { businessNo = cg.cgjh.jhcgbm, amount = cg.cgjh.ysje?.ToString(), content = cg.cgjh.jhcgmc, deptName = cg.cgjh.xqbm };
                        spl.description = _description.ToJson();
                        spl.additionInfoJson = Newtonsoft.Json.JsonConvert.SerializeObject(submit);
                        spl.callbackUrl = "http://ic-xmzc/netapi/CGManage/UpdateStatusCG_Project";
                        spl.callbackInterface = "";

                        //  spl.callbackInterface = "/contract-rule/collection/currency-audit/audit/${taskId}/" + ht.skhtxx.htbh + "/" + ht.skhtxx.htmc + "/" + ht.skhtxx.htlx + "/" + ht.skhtxx.zt + " ";


                        bsp = await JavaApi.startInstanceJavaAPI(spl, await GetICApiInfo());
                        if (bsp)
                        {
                            await BusinessRule.Purchase.CGGL_CG.InsertCG_Project(cg.cgjh);
                            return Success("成功");
                        }
                        else
                        {
                            cg.cgjh.zt = "1";
                            await BusinessRule.Purchase.CGGL_CG.InsertCG_Project(cg.cgjh);
                            return Fail("提交失败，启动工作流异常");
                        }
                    }

                    else
                    {
                        await BusinessRule.Purchase.CGGL_CG.InsertCG_Project(cg.cgjh);

                    }
                    return Success("成功");

                }

            }

            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        //删除
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> DeleteCG_Project(List<string> jhcgbm)
        {
            try
            {
                jhcgbm.Add("autoid10000001");

                string strid = "";
                strid = string.Join("','", jhcgbm.ToArray());

                if (!string.IsNullOrEmpty(strid))
                {
                    strid = "'" + strid + "'";
                }
                await BusinessRule.Purchase.CGGL_CG.DeleteCG_Project(strid);
                return Success("成功");
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        //审批回调
        [HttpPost]
        public async Task<IActionResult> UpdateStatusCG_Project(dynamic spjson)//
        {

            //module，dealUser，approveStatus，businessName，businessId
            try
            {
                _logger.Debug(JsonConvert.SerializeObject(spjson));

                string moduleid = spjson.module;
                string userid = spjson.dealUser;
                string approveStatus = spjson.approveStatus;//UNCHECK, CHECKING,REJECTED,INVALID,CHECKED

                //operation，值：AGREE（同意），REJECT（驳回），INVALID（作废），ACTIVATION（激活），CANCEL（撤销），RESTART（消审）
                string operation = spjson.operation;
                string businessId = spjson.businessId;
                string businessName = spjson.businessName;

                string additionInfo = spjson.additionInfo;
                if (string.IsNullOrEmpty(businessId))
                {
                    return Fail("业务id不能为空");
                }

                //待提交  未审核  审核中  作废  已审核  驳回
                //DRAFT  UNCHECK, CHECKING,INVALID,CHECKED
                string zt = "0";
                if (approveStatus == "DRAFT")
                {
                    zt = "1";
                }
                if (approveStatus == "UNCHECK")
                {
                    zt = "1";
                }
                if (approveStatus == "CHECKING")
                {
                    zt = "9";
                }
                if (approveStatus == "CHECKED")
                {
                    zt = "3";
                }
                if (approveStatus == "REJECT")
                {
                    zt = "4";
                }
                if (approveStatus == "INVALID")
                {
                    zt = "5";
                }
                if (approveStatus == "RESTART")
                {
                    zt = "1";
                }


                await BusinessRule.Purchase.CGGL_CG.UpdateCG_Projectzt(businessId,zt);


                #region 加日志
                LogEntity logEntity = new LogEntity();
                logEntity.F_CategoryId = 3;
                logEntity.F_OperateTypeId = ((int)OperationType.Audit).ToString();
                logEntity.F_OperateType = EnumAttribute.GetDescription(OperationType.Audit);
                logEntity.F_OperateAccount = ContextHelper.GetItem("userName") as string;
                logEntity.F_OperateUserId = ContextHelper.GetItem("userId") as string;
                logEntity.F_Module = Request.Path;
                logEntity.F_IPAddress = Request.HttpContext.Connection.RemoteIpAddress.ToString();
                logEntity.F_ExecuteResult = -1;
                var timeConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };
                logEntity.F_ExecuteResultJson = JsonConvert.SerializeObject(spjson, timeConverter);
                //添加日志
                await LogRule.Write(logEntity);
                #endregion


                //return Success("操作成功");
                return Json(new ResParameter { code = ResponseCode.success, message = "成功" });
            }
            catch (Exception ex)
            {
                return Json(new ResParameter { code = ResponseCode.fail, message = "操作失败" + ex.Message });
                //return Fail("操作失败："+ ex.Message);
            }
        }
        #endregion

        #region"采购立项"
        /// <summary>
        /// 列表页面
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>

        [HttpGet]
        // [AllowAnonymous]
        public async Task<IActionResult> GetCG_Approval([FromQuery] CG_ApprovalQuerry entity)
        {
            try
            {
                _logger.Log(LogLevel.Info, this.Url.Action() + this.Request.QueryString.Value);
                entity.UserID = GetUserId();
                entity.DepartID = await GetDepId("purchase_permission");
                (IEnumerable<dynamic>, int) SelectTable = await BusinessRule.Purchase.CGGL_CG.GetCG_Approval(entity);
                List<string> list = new List<string>();
                foreach (dynamic item in SelectTable.Item1)
                {
                    string id = item.cgxmbm;
                    list.Add(id);
                }

                List<JavaApi.SPSDataItem> spitems = await JavaApi.GetSPStatusJavaAPI(entity.FormCode, GetUserAccount(), list, await GetICApiInfo());
                foreach (dynamic item in SelectTable.Item1)
                {
                    string id = item.cgxmbm;
                    var spstatus = spitems.Where(ii => ii.businessId == id).FirstOrDefault();
                    string status = "unknown";
                    if (item.zt == "1")
                    {
                        status = "draft";

                    }
                    else if (item.zt == "2")
                    {
                        status = "uncheck";

                    }
                    else if (item.zt == "9")
                    {
                        status = "checking";

                    }
                    else if (item.zt == "3")
                    {
                        status = "checked";

                    }
                    else if (item.zt == "4")
                    {
                        status = "reject";

                    }
                    else if (item.zt == "5")
                    {
                        status = "invalid";

                    }

                    else
                    {
                        status = "unfilled";
                    }
                    item.panguData = GetPanGudData(spstatus, status);
                }

                Page pa = new Page();
                pa.records = SelectTable.Item1;
                pa.total = SelectTable.Item2;
                _logger.Log(LogLevel.Info, Success(pa).ToJson());
                return Success(pa);
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Info, ex.Message);
                return Fail(ex.Message);
            }
        }

        //获取详情
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetCG_Approval_Detail(string cgxmbm)
        {
            try
            {


                dynamic dynamic = new ExpandoObject();
                dynamic.cgjh = await BusinessRule.Purchase.CGGL_CG.GetCG_Approval_cgjh(cgxmbm);
                dynamic.xmxx = await BusinessRule.Purchase.CGGL_CG.GetCG_Approval_xmxx(cgxmbm);
                dynamic.wpmx = await BusinessRule.Purchase.CGGL_CG.GetCG_Approval_wpmx(cgxmbm);

                return Success(dynamic);
            }
            catch (Exception)
            {
                return Fail("响应失败");
            }
        }


        [HttpGet]
        //[AllowAnonymous]
        //选择采购计划
        public async Task<IActionResult> SelectCG_Project([FromQuery] CG_ProjectQuerry entity)
        {
            try
            {
                entity.UserID = GetUserId();
                entity.DepartID = await GetDepId("purchase_permission");

               // dynamic dynamic = new ExpandoObject();
                (IEnumerable<dynamic>, int) SelectTable = await BusinessRule.Purchase.CGGL_CG.SelectCG_Project(entity);


                Page pa = new Page();
                pa.records = SelectTable.Item1;
                pa.total = SelectTable.Item2;
                _logger.Log(LogLevel.Info, Success(pa).ToJson());
                return Success(pa);
            }
            catch (Exception)
            {
                return Fail("响应失败");
            }
        }
        //存草稿、提交

        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> SubmitCG_Approval([FromBody] CG_Approval cg)
        {

            try
            {
                if (cg.xmxx.zt == "" || cg.xmxx.zt == null)
                {
                    return Fail("数据状态错误");
                }
                if (cg.xmxx.bmdm == "" || cg.xmxx.bmdm == null)
                {
                    return Fail("数据权限缺失");
                }
                if (cg.xmxx.jhcgbm == "" || cg.xmxx.jhcgbm == null)
                {
                    return Fail("请选择采购计划！");
                }
                if (cg.xmxx.cgxmbm == "" || cg.xmxx.cgxmbm == null)
                {
                    cg.xmxx.cgxmbm = await JavaApi.BusinessBMJavaAPI("purchase_approva", "采购立项", await GetICApiInfo());
                    cg.xmxx.listid = "1";
                    //string listid = "1";
                }
                if (cg.xmxx.cgxmbm == null)
                {
                    return Fail("采购项目编码获取失败");
                }
                if (cg.xmxx.zt == "1")
                {
                    if (await JavaApi.UploadFileJavaAPI(cg.xmxx.cgxmbm, cg.File, await GetICApiInfo()))
                    {

                        await BusinessRule.Purchase.CGGL_CG.InsertCG_Approval_Xm(cg);

                    }
                    else
                    {
                        await BusinessRule.Purchase.CGGL_CG.InsertCG_Approval_Xm(cg);

                    }
                    return Success("成功");
                }
                else
                {

                    if (await JavaApi.UploadFileJavaAPI(cg.xmxx.cgxmbm, cg.File, await GetICApiInfo()))
                    {
                        CG_Submit submit = new CG_Submit();
                        submit.submitid = cg.xmxx.cgxmbm;
                        submit.submitmc = cg.xmxx.cgxmmc;
                        submit.submitje = cg.xmxx.yjcgzje.ToString();
                        submit.submitlx = "采购立项";
                        bool bsp = false;
                        JavaApi.SPLEnt spl = new JavaApi.SPLEnt();
                        spl.businessName = "采购立项";
                        spl.businessId = cg.xmxx.cgxmbm;
                        // spl.publicParamKey = "FEE_PROCESS";
                        spl.formCode = cg.File.code;

                        //spl.description = Newtonsoft.Json.JsonConvert.SerializeObject(htsmbmit);
                        JavaApi.SPLEnt.Auditdescription _description = new JavaApi.SPLEnt.Auditdescription() { businessNo = cg.xmxx.cgxmbm, amount = cg.xmxx.yjcgzje?.ToString(), content = cg.xmxx.cgxmmc, deptName = cg.xmxx.xqbm };
                        spl.description = _description.ToJson();
                        spl.additionInfoJson = Newtonsoft.Json.JsonConvert.SerializeObject(submit);
                        spl.callbackUrl = "http://ic-xmzc/netapi/CGManage/UpdateStatusCG_Approval";
                        spl.callbackInterface = "";

                        //  spl.callbackInterface = "/contract-rule/collection/currency-audit/audit/${taskId}/" + ht.skhtxx.htbh + "/" + ht.skhtxx.htmc + "/" + ht.skhtxx.htlx + "/" + ht.skhtxx.zt + " ";


                        bsp = await JavaApi.startInstanceJavaAPI(spl, await GetICApiInfo());
                        if (bsp)
                        {
                            await BusinessRule.Purchase.CGGL_CG.InsertCG_Approval_Xm(cg);
                            return Success("成功");
                        }
                        else
                        {
                            cg.xmxx.zt = "1";
                            await BusinessRule.Purchase.CGGL_CG.InsertCG_Approval_Xm(cg);
                            return Fail("提交失败，启动工作流异常");
                        }
                    }

                    else
                    {
                        await BusinessRule.Purchase.CGGL_CG.InsertCG_Approval_Xm(cg);

                    }
                    return Success("成功");

                }

            }

            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        //删除
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> DeleteCG_Approval(List<string> cgxmbm)
        {
            try
            {
                cgxmbm.Add("autoid10000001");

                string strid = "";
                strid = string.Join("','", cgxmbm.ToArray());

                if (!string.IsNullOrEmpty(strid))
                {
                    strid = "'" + strid + "'";
                }
                await BusinessRule.Purchase.CGGL_CG.DeleteCG_Approval(strid);
                return Success("成功");
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        //审批回调
        [HttpPost]
        public async Task<IActionResult> UpdateStatusCG_Approval(dynamic spjson)//
        {

            //module，dealUser，approveStatus，businessName，businessId
            try
            {
                _logger.Debug(JsonConvert.SerializeObject(spjson));

                string moduleid = spjson.module;
                string userid = spjson.dealUser;
                string approveStatus = spjson.approveStatus;//UNCHECK, CHECKING,REJECTED,INVALID,CHECKED

                //operation，值：AGREE（同意），REJECT（驳回），INVALID（作废），ACTIVATION（激活），CANCEL（撤销），RESTART（消审）
                string operation = spjson.operation;
                string businessId = spjson.businessId;
                string businessName = spjson.businessName;

                string additionInfo = spjson.additionInfo;
                if (string.IsNullOrEmpty(businessId))
                {
                    return Fail("业务id不能为空");
                }

                //待提交  未审核  审核中  作废  已审核  驳回
                //DRAFT  UNCHECK, CHECKING,INVALID,CHECKED
                string zt = "0";
                if (approveStatus == "DRAFT")
                {
                    zt = "1";
                }
                if (approveStatus == "UNCHECK")
                {
                    zt = "1";
                }
                if (approveStatus == "CHECKING")
                {
                    zt = "9";
                }
                if (approveStatus == "CHECKED")
                {
                    zt = "3";
                }
                if (approveStatus == "REJECT")
                {
                    zt = "4";
                }
                if (approveStatus == "INVALID")
                {
                    zt = "5";
                }
                if (approveStatus == "RESTART")
                {
                    zt = "1";
                }


                await BusinessRule.Purchase.CGGL_CG.UpdateCG_Approvalzt(businessId, zt);


                #region 加日志
                LogEntity logEntity = new LogEntity();
                logEntity.F_CategoryId = 3;
                logEntity.F_OperateTypeId = ((int)OperationType.Audit).ToString();
                logEntity.F_OperateType = EnumAttribute.GetDescription(OperationType.Audit);
                logEntity.F_OperateAccount = ContextHelper.GetItem("userName") as string;
                logEntity.F_OperateUserId = ContextHelper.GetItem("userId") as string;
                logEntity.F_Module = Request.Path;
                logEntity.F_IPAddress = Request.HttpContext.Connection.RemoteIpAddress.ToString();
                logEntity.F_ExecuteResult = -1;
                var timeConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };
                logEntity.F_ExecuteResultJson = JsonConvert.SerializeObject(spjson, timeConverter);
                //添加日志
                await LogRule.Write(logEntity);
                #endregion


                //return Success("操作成功");
                return Json(new ResParameter { code = ResponseCode.success, message = "成功" });
            }
            catch (Exception ex)
            {
                return Json(new ResParameter { code = ResponseCode.fail, message = "操作失败" + ex.Message });
                //return Fail("操作失败："+ ex.Message);
            }
        }
        #endregion

        #region"代理机构申请"
        /// <summary>
        /// 列表页面
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>

        [HttpGet]
        // [AllowAnonymous]
        public async Task<IActionResult> GetCG_Agency([FromQuery] CG_AgencyQuerry entity)
        {
            try
            {
                _logger.Log(LogLevel.Info, this.Url.Action() + this.Request.QueryString.Value);
                entity.UserID = GetUserId();
                entity.DepartID = await GetDepId("purchase_permission");
                (IEnumerable<dynamic>, int) SelectTable = await BusinessRule.Purchase.CGGL_CG.GetCG_Agency(entity);
                List<string> list = new List<string>();
                foreach (dynamic item in SelectTable.Item1)
                {
                    string id = item.djbm;
                    list.Add(id);
                }

                List<JavaApi.SPSDataItem> spitems = await JavaApi.GetSPStatusJavaAPI(entity.FormCode, GetUserAccount(), list, await GetICApiInfo());
                foreach (dynamic item in SelectTable.Item1)
                {
                    string id = item.djbm;
                    var spstatus = spitems.Where(ii => ii.businessId == id).FirstOrDefault();
                    string status = "unknown";
                    if (item.zt == "1")
                    {
                        status = "draft";

                    }
                    else if (item.zt == "2")
                    {
                        status = "uncheck";

                    }
                    else if (item.zt == "9")
                    {
                        status = "checking";

                    }
                    else if (item.zt == "3")
                    {
                        status = "checked";

                    }
                    else if (item.zt == "4")
                    {
                        status = "reject";

                    }
                    else if (item.zt == "5")
                    {
                        status = "invalid";

                    }

                    else
                    {
                        status = "unfilled";
                    }
                    item.panguData = GetPanGudData(spstatus, status);
                }

                Page pa = new Page();
                pa.records = SelectTable.Item1;
                pa.total = SelectTable.Item2;
                _logger.Log(LogLevel.Info, Success(pa).ToJson());
                return Success(pa);
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Info, ex.Message);
                return Fail(ex.Message);
            }
        }

        //获取详情
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetCG_Agency_Detail(string djbm)
        {
            try
            {


                dynamic dynamic = new ExpandoObject();
                dynamic.cgxm = await BusinessRule.Purchase.CGGL_CG.GetCG_Agency_cgxm(djbm);
                dynamic.dljg = await BusinessRule.Purchase.CGGL_CG.GetCG_Agency_dljg(djbm);
             

                return Success(dynamic);
            }
            catch (Exception)
            {
                return Fail("响应失败");
            }
        }

        //选择采购项目
        [HttpGet]
        //[AllowAnonymous]
        public async Task<IActionResult> SelectCG_Approval([FromQuery] CG_ApprovalQuerry entity)
        {
            try
            {
                entity.UserID = GetUserId();
                entity.DepartID = await GetDepId("purchase_permission");

                // dynamic dynamic = new ExpandoObject();
                (IEnumerable<dynamic>, int) SelectTable = await BusinessRule.Purchase.CGGL_CG.SelectCG_Approval(entity);


                Page pa = new Page();
                pa.records = SelectTable.Item1;
                pa.total = SelectTable.Item2;
                _logger.Log(LogLevel.Info, Success(pa).ToJson());
                return Success(pa);
            }
            catch (Exception)
            {
                return Fail("响应失败");
            }
        }

 

        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> SubmitCG_Agency([FromBody] CG_Agency_Sub dljg)
        {

            try
            {
                if (dljg.agency.zt == "" || dljg.agency.zt == null)
                {
                    return Fail("数据状态错误");
                }
                if (dljg.agency.bmdm == "" || dljg.agency.bmdm == null)
                {
                    return Fail("数据权限缺失");
                }
                if (dljg.agency.cgxmbm == "" || dljg.agency.cgxmbm == null)
                {
                    return Fail("请选择采购项目！");
                }
                if (dljg.agency.djbm == "" || dljg.agency.djbm == null)
                {
                    dljg.agency.djbm = await JavaApi.BusinessBMJavaAPI("purchase_agence", "代理机构", await GetICApiInfo());
                    dljg.agency.listid = "1";
                    //string listid = "1";
                }
                if (dljg.agency.djbm == null)
                {
                    return Fail("单据编码获取失败");
                }
                if (dljg.agency.zt == "1")
                {
                    if (await JavaApi.UploadFileJavaAPI(dljg.agency.djbm, dljg.File, await GetICApiInfo()))
                    {

                        await BusinessRule.Purchase.CGGL_CG.InsertCG_Agency(dljg.agency);

                    }
                    else
                    {
                        await BusinessRule.Purchase.CGGL_CG.InsertCG_Agency(dljg.agency);

                    }
                    return Success("成功");
                }
                else
                {

                    if (await JavaApi.UploadFileJavaAPI(dljg.agency.djbm, dljg.File, await GetICApiInfo()))
                    {
                        CG_Submit submit = new CG_Submit();
                        submit.submitid = dljg.agency.djbm;
                        submit.submitmc = dljg.agency.dljgmc;
                       // submit.submitje = cg.xmxx.yjcgzje.ToString();
                        submit.submitlx = "代理机构申请";
                        bool bsp = false;
                        JavaApi.SPLEnt spl = new JavaApi.SPLEnt();
                        spl.businessName = "代理机构申请";
                        spl.businessId = dljg.agency.djbm;
                        // spl.publicParamKey = "FEE_PROCESS";
                        spl.formCode = dljg.File.code;

                        //spl.description = Newtonsoft.Json.JsonConvert.SerializeObject(htsmbmit);
                        JavaApi.SPLEnt.Auditdescription _description = new JavaApi.SPLEnt.Auditdescription() { businessNo = dljg.agency.djbm, amount = "0", content = dljg.agency.dljgmc, deptName = dljg.agency.tjr};
                        spl.description = _description.ToJson();
                        spl.additionInfoJson = Newtonsoft.Json.JsonConvert.SerializeObject(submit);
                        spl.callbackUrl = "http://ic-xmzc/netapi/CGManage/UpdateStatusCG_Agency";
                        spl.callbackInterface = "";

                        //  spl.callbackInterface = "/contract-rule/collection/currency-audit/audit/${taskId}/" + ht.skhtxx.htbh + "/" + ht.skhtxx.htmc + "/" + ht.skhtxx.htlx + "/" + ht.skhtxx.zt + " ";


                        bsp = await JavaApi.startInstanceJavaAPI(spl, await GetICApiInfo());
                        if (bsp)
                        {
                            await BusinessRule.Purchase.CGGL_CG.InsertCG_Agency(dljg.agency);
                            return Success("成功");
                        }
                        else
                        {
                            dljg.agency.zt = "1";
                            await BusinessRule.Purchase.CGGL_CG.InsertCG_Agency(dljg.agency);
                            return Fail("提交失败，启动工作流异常");
                        }
                    }

                    else
                    {
                        await BusinessRule.Purchase.CGGL_CG.InsertCG_Agency(dljg.agency);

                    }
                    return Success("成功");

                }

            }

            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

   
        //删除
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> DeleteCG_Agency(List<string> djbm)
        {
            try
            {
                djbm.Add("autoid10000001");

                string strid = "";
                strid = string.Join("','", djbm.ToArray());

                if (!string.IsNullOrEmpty(strid))
                {
                    strid = "'" + strid + "'";
                }
                await BusinessRule.Purchase.CGGL_CG.DeleteCG_Agency(strid);
                return Success("成功");
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        //审批回调
        [HttpPost]
        public async Task<IActionResult> UpdateStatusCG_Agency(dynamic spjson)//
        {

            //module，dealUser，approveStatus，businessName，businessId
            try
            {
                _logger.Debug(JsonConvert.SerializeObject(spjson));

                string moduleid = spjson.module;
                string userid = spjson.dealUser;
                string approveStatus = spjson.approveStatus;//UNCHECK, CHECKING,REJECTED,INVALID,CHECKED

                //operation，值：AGREE（同意），REJECT（驳回），INVALID（作废），ACTIVATION（激活），CANCEL（撤销），RESTART（消审）
                string operation = spjson.operation;
                string businessId = spjson.businessId;
                string businessName = spjson.businessName;

                string additionInfo = spjson.additionInfo;
                if (string.IsNullOrEmpty(businessId))
                {
                    return Fail("业务id不能为空");
                }

                //待提交  未审核  审核中  作废  已审核  驳回
                //DRAFT  UNCHECK, CHECKING,INVALID,CHECKED
                string zt = "0";
                if (approveStatus == "DRAFT")
                {
                    zt = "1";
                }
                if (approveStatus == "UNCHECK")
                {
                    zt = "1";
                }
                if (approveStatus == "CHECKING")
                {
                    zt = "9";
                }
                if (approveStatus == "CHECKED")
                {
                    zt = "3";
                }
                if (approveStatus == "REJECT")
                {
                    zt = "4";
                }
                if (approveStatus == "INVALID")
                {
                    zt = "5";
                }
                if (approveStatus == "RESTART")
                {
                    zt = "1";
                }


                await BusinessRule.Purchase.CGGL_CG.UpdateCG_Agencyzt(businessId, zt);


                #region 加日志
                LogEntity logEntity = new LogEntity();
                logEntity.F_CategoryId = 3;
                logEntity.F_OperateTypeId = ((int)OperationType.Audit).ToString();
                logEntity.F_OperateType = EnumAttribute.GetDescription(OperationType.Audit);
                logEntity.F_OperateAccount = ContextHelper.GetItem("userName") as string;
                logEntity.F_OperateUserId = ContextHelper.GetItem("userId") as string;
                logEntity.F_Module = Request.Path;
                logEntity.F_IPAddress = Request.HttpContext.Connection.RemoteIpAddress.ToString();
                logEntity.F_ExecuteResult = -1;
                var timeConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };
                logEntity.F_ExecuteResultJson = JsonConvert.SerializeObject(spjson, timeConverter);
                //添加日志
                await LogRule.Write(logEntity);
                #endregion


                //return Success("操作成功");
                return Json(new ResParameter { code = ResponseCode.success, message = "成功" });
            }
            catch (Exception ex)
            {
                return Json(new ResParameter { code = ResponseCode.fail, message = "操作失败" + ex.Message });
                //return Fail("操作失败："+ ex.Message);
            }
        }

        //获取代理机构名称（下拉框）
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetCG_AgencyName()
        {
            try
            {


                dynamic dynamic = new ExpandoObject();
                dynamic.agency = await BusinessRule.Purchase.CGGL_CG.GetCG_AgencyName();
               

                return Success(dynamic);
            }
            catch (Exception)
            {
                return Fail("响应失败");
            }
        }
        #endregion

        #region"拆分标段"
        /// <summary>
        /// 列表页面
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>

        [HttpGet]
        // [AllowAnonymous]
        public async Task<IActionResult> GetCG_Lot([FromQuery] CG_LotQuerry entity)
        {
            try
            {
                _logger.Log(LogLevel.Info, this.Url.Action() + this.Request.QueryString.Value);
                entity.UserID = GetUserId();
                entity.DepartID = await GetDepId("purchase_permission");
                (IEnumerable<dynamic>, int) SelectTable = await BusinessRule.Purchase.CGGL_CG.GetCG_Lot(entity);
                List<string> list = new List<string>();
                foreach (dynamic item in SelectTable.Item1)
                {
                    string id = item.djbm;
                    list.Add(id);
                }

                List<JavaApi.SPSDataItem> spitems = await JavaApi.GetSPStatusJavaAPI(entity.FormCode, GetUserAccount(), list, await GetICApiInfo());
                foreach (dynamic item in SelectTable.Item1)
                {
                    string id = item.djbm;
                    var spstatus = spitems.Where(ii => ii.businessId == id).FirstOrDefault();
                    string status = "unknown";
                    if (item.zt == "1")
                    {
                        status = "draft";

                    }
                    else if (item.zt == "2")
                    {
                        status = "uncheck";

                    }
                    else if (item.zt == "9")
                    {
                        status = "checking";

                    }
                    else if (item.zt == "3")
                    {
                        status = "checked";

                    }
                    else if (item.zt == "4")
                    {
                        status = "reject";

                    }
                    else if (item.zt == "5")
                    {
                        status = "invalid";

                    }

                    else
                    {
                        status = "unfilled";
                    }
                    item.panguData = GetPanGudData(spstatus, status);
                }

                Page pa = new Page();
                pa.records = SelectTable.Item1;
                pa.total = SelectTable.Item2;
                _logger.Log(LogLevel.Info, Success(pa).ToJson());
                return Success(pa);
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Info, ex.Message);
                return Fail(ex.Message);
            }
        }

       
        //获取详情
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetCG_Lot_Detail(string djbm)
        {
            try
            {


                dynamic dynamic = new ExpandoObject();
                dynamic.cgxm = await BusinessRule.Purchase.CGGL_CG.GetCG_Lot_cgxm(djbm);
                dynamic.list = await BusinessRule.Purchase.CGGL_CG.GetCG_Lot_list(djbm);
                dynamic.lot = await BusinessRule.Purchase.CGGL_CG.GetCG_Lot_detail(djbm);


                return Success(dynamic);
            }
            catch (Exception)
            {
                return Fail("响应失败");
            }
        }



        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> SubmitCG_Lot([FromBody] CG_Lot lot)
        {

            try
            {
                if (lot.list.zt == "" || lot.list.zt == null)
                {
                    return Fail("数据状态错误");
                }
                if (lot.list.bmdm == "" || lot.list.bmdm == null)
                {
                    return Fail("数据权限缺失");
                }
                if (lot.list.cgxmbm == "" || lot.list.cgxmbm == null)
                {
                    return Fail("请选择采购项目！");
                }
                if (lot.list.djbm == "" || lot.list.djbm == null)
                {
                    lot.list.djbm = await JavaApi.BusinessBMJavaAPI("purchase_lot", "拆分标段", await GetICApiInfo());
                    lot.list.listid = "1";
                    //string listid = "1";
                }
                if (lot.list.djbm == null)
                {
                    return Fail("单据编码获取失败");
                }
                if (lot.list.zt == "1")
                {
                    if (await JavaApi.UploadFileJavaAPI(lot.list.djbm, lot.File, await GetICApiInfo()))
                    {

                        await BusinessRule.Purchase.CGGL_CG.InsertCG_Lot(lot);

                    }
                    else
                    {
                        await BusinessRule.Purchase.CGGL_CG.InsertCG_Lot(lot);

                    }
                    return Success("成功");
                }
                else
                {

                    if (await JavaApi.UploadFileJavaAPI(lot.list.djbm, lot.File, await GetICApiInfo()))
                    {
                        CG_Submit submit = new CG_Submit();
                        submit.submitid = lot.list.djbm;
                        submit.submitmc = lot.list.cgxmmc;
                        // submit.submitje = cg.xmxx.yjcgzje.ToString();
                        submit.submitlx = "拆分标段";
                        bool bsp = false;
                        JavaApi.SPLEnt spl = new JavaApi.SPLEnt();
                        spl.businessName = "拆分标段";
                        spl.businessId = lot.list.djbm;
                        // spl.publicParamKey = "FEE_PROCESS";
                        spl.formCode = lot.File.code;

                        //spl.description = Newtonsoft.Json.JsonConvert.SerializeObject(htsmbmit);
                        JavaApi.SPLEnt.Auditdescription _description = new JavaApi.SPLEnt.Auditdescription() { businessNo = lot.list.djbm, amount = "0", content = lot.list.cgxmmc, deptName = lot.list.tjr };
                        spl.description = _description.ToJson();
                        spl.additionInfoJson = Newtonsoft.Json.JsonConvert.SerializeObject(submit);
                        spl.callbackUrl = "http://ic-xmzc/netapi/CGManage/UpdateStatusCG_Lot";
                        spl.callbackInterface = "";

                        //  spl.callbackInterface = "/contract-rule/collection/currency-audit/audit/${taskId}/" + ht.skhtxx.htbh + "/" + ht.skhtxx.htmc + "/" + ht.skhtxx.htlx + "/" + ht.skhtxx.zt + " ";


                        bsp = await JavaApi.startInstanceJavaAPI(spl, await GetICApiInfo());
                        if (bsp)
                        {
                            await BusinessRule.Purchase.CGGL_CG.InsertCG_Lot(lot);
                            return Success("成功");
                        }
                        else
                        {
                            lot.list.zt = "1";
                            await BusinessRule.Purchase.CGGL_CG.InsertCG_Lot(lot);
                            return Fail("提交失败，启动工作流异常");
                        }
                    }

                    else
                    {
                        await BusinessRule.Purchase.CGGL_CG.InsertCG_Lot(lot);

                    }
                    return Success("成功");

                }

            }

            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }


        //删除
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> DeleteCG_Lot(List<string> cgxmbm)
        {
            try
            {
                cgxmbm.Add("autoid10000001");

                string strid = "";
                strid = string.Join("','", cgxmbm.ToArray());

                if (!string.IsNullOrEmpty(strid))
                {
                    strid = "'" + strid + "'";
                }
                await BusinessRule.Purchase.CGGL_CG.DeleteCG_Lot(strid);
                return Success("成功");
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        //审批回调
        [HttpPost]
        public async Task<IActionResult> UpdateStatusCG_Lot(dynamic spjson)//
        {

            //module，dealUser，approveStatus，businessName，businessId
            try
            {
                _logger.Debug(JsonConvert.SerializeObject(spjson));

                string moduleid = spjson.module;
                string userid = spjson.dealUser;
                string approveStatus = spjson.approveStatus;//UNCHECK, CHECKING,REJECTED,INVALID,CHECKED

                //operation，值：AGREE（同意），REJECT（驳回），INVALID（作废），ACTIVATION（激活），CANCEL（撤销），RESTART（消审）
                string operation = spjson.operation;
                string businessId = spjson.businessId;
                string businessName = spjson.businessName;

                string additionInfo = spjson.additionInfo;
                if (string.IsNullOrEmpty(businessId))
                {
                    return Fail("业务id不能为空");
                }

                //待提交  未审核  审核中  作废  已审核  驳回
                //DRAFT  UNCHECK, CHECKING,INVALID,CHECKED
                string zt = "0";
                if (approveStatus == "DRAFT")
                {
                    zt = "1";
                }
                if (approveStatus == "UNCHECK")
                {
                    zt = "1";
                }
                if (approveStatus == "CHECKING")
                {
                    zt = "9";
                }
                if (approveStatus == "CHECKED")
                {
                    zt = "3";
                }
                if (approveStatus == "REJECT")
                {
                    zt = "4";
                }
                if (approveStatus == "INVALID")
                {
                    zt = "5";
                }
                if (approveStatus == "RESTART")
                {
                    zt = "1";
                }


                await BusinessRule.Purchase.CGGL_CG.UpdateCG_Lotzt(businessId, zt);


                #region 加日志
                LogEntity logEntity = new LogEntity();
                logEntity.F_CategoryId = 3;
                logEntity.F_OperateTypeId = ((int)OperationType.Audit).ToString();
                logEntity.F_OperateType = EnumAttribute.GetDescription(OperationType.Audit);
                logEntity.F_OperateAccount = ContextHelper.GetItem("userName") as string;
                logEntity.F_OperateUserId = ContextHelper.GetItem("userId") as string;
                logEntity.F_Module = Request.Path;
                logEntity.F_IPAddress = Request.HttpContext.Connection.RemoteIpAddress.ToString();
                logEntity.F_ExecuteResult = -1;
                var timeConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };
                logEntity.F_ExecuteResultJson = JsonConvert.SerializeObject(spjson, timeConverter);
                //添加日志
                await LogRule.Write(logEntity);
                #endregion


                //return Success("操作成功");
                return Json(new ResParameter { code = ResponseCode.success, message = "成功" });
            }
            catch (Exception ex)
            {
                return Json(new ResParameter { code = ResponseCode.fail, message = "操作失败" + ex.Message });
                //return Fail("操作失败："+ ex.Message);
            }
        }
        #endregion

        #region"招标申请"
        /// <summary>
        /// 列表页面
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>

        [HttpGet]
        // [AllowAnonymous]
        public async Task<IActionResult> GetCG_Invite([FromQuery] CG_InviteQuerry entity)
        {
            try
            {
                _logger.Log(LogLevel.Info, this.Url.Action() + this.Request.QueryString.Value);
                entity.UserID = GetUserId();
                entity.DepartID = await GetDepId("purchase_permission");
                (IEnumerable<dynamic>, int) SelectTable = await BusinessRule.Purchase.CGGL_CG.GetCG_Invite(entity);
                List<string> list = new List<string>();
                foreach (dynamic item in SelectTable.Item1)
                {
                    string id = item.djbm;
                    list.Add(id);
                }

                List<JavaApi.SPSDataItem> spitems = await JavaApi.GetSPStatusJavaAPI(entity.FormCode, GetUserAccount(), list, await GetICApiInfo());
                foreach (dynamic item in SelectTable.Item1)
                {
                    string id = item.djbm;
                    var spstatus = spitems.Where(ii => ii.businessId == id).FirstOrDefault();
                    string status = "unknown";
                    if (item.zt == "1")
                    {
                        status = "draft";

                    }
                    else if (item.zt == "2")
                    {
                        status = "uncheck";

                    }
                    else if (item.zt == "9")
                    {
                        status = "checking";

                    }
                    else if (item.zt == "3")
                    {
                        status = "checked";

                    }
                    else if (item.zt == "4")
                    {
                        status = "reject";

                    }
                    else if (item.zt == "5")
                    {
                        status = "invalid";

                    }

                    else
                    {
                        status = "unfilled";
                    }
                    item.panguData = GetPanGudData(spstatus, status);
                }

                Page pa = new Page();
                pa.records = SelectTable.Item1;
                pa.total = SelectTable.Item2;
                _logger.Log(LogLevel.Info, Success(pa).ToJson());
                return Success(pa);
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Info, ex.Message);
                return Fail(ex.Message);
            }
        }

        
        //获取详情
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetCG_Invite_Detail(string djbm)
        {
            try
            {


                dynamic dynamic = new ExpandoObject();
                dynamic.bdxx = await BusinessRule.Purchase.CGGL_CG.GetCG_Invite_bdxx(djbm);
                dynamic.zbxx = await BusinessRule.Purchase.CGGL_CG.GetCG_Invite_zbxx(djbm);


                return Success(dynamic);
            }
            catch (Exception)
            {
                return Fail("响应失败");
            }
        }

        //选择标段
        
        [HttpGet]
        //[AllowAnonymous]
        public async Task<IActionResult> SelectCG_Lot([FromQuery] CG_LotQuerry entity)
        {
            try
            {
                entity.UserID = GetUserId();
                entity.DepartID = await GetDepId("purchase_permission");

                // dynamic dynamic = new ExpandoObject();
                (IEnumerable<dynamic>, int) SelectTable = await BusinessRule.Purchase.CGGL_CG.SelectCG_Lot(entity);


                Page pa = new Page();
                pa.records = SelectTable.Item1;
                pa.total = SelectTable.Item2;
                _logger.Log(LogLevel.Info, Success(pa).ToJson());
                return Success(pa);
            }
            catch (Exception)
            {
                return Fail("响应失败");
            }
        }


        //存草稿、提交

        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> SubmitCG_Invite([FromBody] CG_Invite_Sub bd)
        {

            try
            {
                if (bd.invite.zt == "" || bd.invite.zt == null)
                {
                    return Fail("数据状态错误");
                }
                if (bd.invite.bmdm == "" || bd.invite.bmdm == null)
                {
                    return Fail("数据权限缺失");
                }
                if (bd.invite.bdid == "" || bd.invite.bdid == null)
                {
                    return Fail("请选择采购标段！");
                }
                if (bd.invite.djbm == "" || bd.invite.djbm == null)
                {
                    bd.invite.djbm = await JavaApi.BusinessBMJavaAPI("purchase_invite", "招标申请", await GetICApiInfo());
                    bd.invite.listid = "1";
                    //string listid = "1";
                }
                if (bd.invite.djbm == null)
                {
                    return Fail("单据编码获取失败");
                }
                if (bd.invite.zt == "1")
                {
                    if (await JavaApi.UploadFileJavaAPI(bd.invite.djbm, bd.File, await GetICApiInfo()))
                    {

                        await BusinessRule.Purchase.CGGL_CG.InsertCG_Invite(bd.invite);

                    }
                    else
                    {
                        await BusinessRule.Purchase.CGGL_CG.InsertCG_Invite(bd.invite);

                    }
                    return Success("成功");
                }
                else
                {

                    if (await JavaApi.UploadFileJavaAPI(bd.invite.djbm, bd.File, await GetICApiInfo()))
                    {
                        CG_Submit submit = new CG_Submit();
                        submit.submitid = bd.invite.djbm;
                        submit.submitmc = bd.invite.zbmc;
                         submit.submitje = bd.invite.ysje.ToString();
                        submit.submitlx = "招标申请";
                        bool bsp = false;
                        JavaApi.SPLEnt spl = new JavaApi.SPLEnt();
                        spl.businessName = "招标申请";
                        spl.businessId = bd.invite.djbm;
                        // spl.publicParamKey = "FEE_PROCESS";
                        spl.formCode = bd.File.code;

                        //spl.description = Newtonsoft.Json.JsonConvert.SerializeObject(htsmbmit);
                        JavaApi.SPLEnt.Auditdescription _description = new JavaApi.SPLEnt.Auditdescription() { businessNo = bd.invite.djbm, amount = bd.invite.ysje.ToString(), content = bd.invite.zbmc, deptName = bd.invite.tjr };
                        spl.description = _description.ToJson();
                        spl.additionInfoJson = Newtonsoft.Json.JsonConvert.SerializeObject(submit);
                        spl.callbackUrl = "http://ic-xmzc/netapi/CGManage/UpdateStatusCG_Invite";
                        spl.callbackInterface = "";

                        //  spl.callbackInterface = "/contract-rule/collection/currency-audit/audit/${taskId}/" + ht.skhtxx.htbh + "/" + ht.skhtxx.htmc + "/" + ht.skhtxx.htlx + "/" + ht.skhtxx.zt + " ";


                        bsp = await JavaApi.startInstanceJavaAPI(spl, await GetICApiInfo());
                        if (bsp)
                        {
                            await BusinessRule.Purchase.CGGL_CG.InsertCG_Invite(bd.invite);
                            return Success("成功");
                        }
                        else
                        {
                            bd.invite.zt = "1";
                            await BusinessRule.Purchase.CGGL_CG.InsertCG_Invite(bd.invite);
                            return Fail("提交失败，启动工作流异常");
                        }
                    }

                    else
                    {
                        await BusinessRule.Purchase.CGGL_CG.InsertCG_Invite(bd.invite);

                    }
                    return Success("成功");

                }

            }

            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        //删除
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> DeleteCG_Invite(List<string> djbm)
        {
            try
            {
                djbm.Add("autoid10000001");

                string strid = "";
                strid = string.Join("','", djbm.ToArray());

                if (!string.IsNullOrEmpty(strid))
                {
                    strid = "'" + strid + "'";
                }
                await BusinessRule.Purchase.CGGL_CG.DeleteCG_Invite(strid);
                return Success("成功");
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        //审批回调
        [HttpPost]
        public async Task<IActionResult> UpdateStatusCG_Invite(dynamic spjson)//
        {

            //module，dealUser，approveStatus，businessName，businessId
            try
            {
                _logger.Debug(JsonConvert.SerializeObject(spjson));

                string moduleid = spjson.module;
                string userid = spjson.dealUser;
                string approveStatus = spjson.approveStatus;//UNCHECK, CHECKING,REJECTED,INVALID,CHECKED

                //operation，值：AGREE（同意），REJECT（驳回），INVALID（作废），ACTIVATION（激活），CANCEL（撤销），RESTART（消审）
                string operation = spjson.operation;
                string businessId = spjson.businessId;
                string businessName = spjson.businessName;

                string additionInfo = spjson.additionInfo;
                if (string.IsNullOrEmpty(businessId))
                {
                    return Fail("业务id不能为空");
                }

                //待提交  未审核  审核中  作废  已审核  驳回
                //DRAFT  UNCHECK, CHECKING,INVALID,CHECKED
                string zt = "0";
                if (approveStatus == "DRAFT")
                {
                    zt = "1";
                }
                if (approveStatus == "UNCHECK")
                {
                    zt = "1";
                }
                if (approveStatus == "CHECKING")
                {
                    zt = "9";
                }
                if (approveStatus == "CHECKED")
                {
                    zt = "3";
                }
                if (approveStatus == "REJECT")
                {
                    zt = "4";
                }
                if (approveStatus == "INVALID")
                {
                    zt = "5";
                }
                if (approveStatus == "RESTART")
                {
                    zt = "1";
                }


                await BusinessRule.Purchase.CGGL_CG.UpdateCG_Invitezt(businessId, zt);


                #region 加日志
                LogEntity logEntity = new LogEntity();
                logEntity.F_CategoryId = 3;
                logEntity.F_OperateTypeId = ((int)OperationType.Audit).ToString();
                logEntity.F_OperateType = EnumAttribute.GetDescription(OperationType.Audit);
                logEntity.F_OperateAccount = ContextHelper.GetItem("userName") as string;
                logEntity.F_OperateUserId = ContextHelper.GetItem("userId") as string;
                logEntity.F_Module = Request.Path;
                logEntity.F_IPAddress = Request.HttpContext.Connection.RemoteIpAddress.ToString();
                logEntity.F_ExecuteResult = -1;
                var timeConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };
                logEntity.F_ExecuteResultJson = JsonConvert.SerializeObject(spjson, timeConverter);
                //添加日志
                await LogRule.Write(logEntity);
                #endregion


                //return Success("操作成功");
                return Json(new ResParameter { code = ResponseCode.success, message = "成功" });
            }
            catch (Exception ex)
            {
                return Json(new ResParameter { code = ResponseCode.fail, message = "操作失败" + ex.Message });
                //return Fail("操作失败："+ ex.Message);
            }
        }
        #endregion

        #region"中标管理"
        /// <summary>
        /// 列表页面
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>

        [HttpGet]
        // [AllowAnonymous]
        public async Task<IActionResult> GetCG_Bidder([FromQuery] CG_BidderQuerry entity)
        {
            try
            {
                _logger.Log(LogLevel.Info, this.Url.Action() + this.Request.QueryString.Value);
                entity.UserID = GetUserId();
                entity.DepartID = await GetDepId("purchase_permission");
                (IEnumerable<dynamic>, int) SelectTable = await BusinessRule.Purchase.CGGL_CG.GetCG_Bidder(entity);
                List<string> list = new List<string>();
                foreach (dynamic item in SelectTable.Item1)
                {
                    string id = item.djbm;
                    list.Add(id);
                }

                List<JavaApi.SPSDataItem> spitems = await JavaApi.GetSPStatusJavaAPI(entity.FormCode, GetUserAccount(), list, await GetICApiInfo());
                foreach (dynamic item in SelectTable.Item1)
                {
                    string id = item.djbm;
                    var spstatus = spitems.Where(ii => ii.businessId == id).FirstOrDefault();
                    string status = "unknown";
                    if (item.zt == "1")
                    {
                        status = "draft";

                    }
                    else if (item.zt == "2")
                    {
                        status = "uncheck";

                    }
                    else if (item.zt == "9")
                    {
                        status = "checking";

                    }
                    else if (item.zt == "3")
                    {
                        status = "checked";

                    }
                    else if (item.zt == "4")
                    {
                        status = "reject";

                    }
                    else if (item.zt == "5")
                    {
                        status = "invalid";

                    }

                    else
                    {
                        status = "unfilled";
                    }
                    item.panguData = GetPanGudData(spstatus, status);
                }

                Page pa = new Page();
                pa.records = SelectTable.Item1;
                pa.total = SelectTable.Item2;
                _logger.Log(LogLevel.Info, Success(pa).ToJson());
                return Success(pa);
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Info, ex.Message);
                return Fail(ex.Message);
            }
        }

        //获取详情
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetCG_Bidder_Detail(string djbm)
        {
            try
            {


                dynamic dynamic = new ExpandoObject();
                dynamic.zbsq = await BusinessRule.Purchase.CGGL_CG.GetCG_Bidder_zbsq(djbm);
                dynamic.tbdw = await BusinessRule.Purchase.CGGL_CG.GetCG_Bidder_tbdw(djbm);
                dynamic.zbxx = await BusinessRule.Purchase.CGGL_CG.GetCG_Bidder_zbxx(djbm);

                return Success(dynamic);
            }
            catch (Exception)
            {
                return Fail("响应失败");
            }
        }


        //选择招标申请

        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> SelectCG_Invite([FromQuery] CG_InviteQuerry entity)
        {
            try
            {
                entity.UserID = GetUserId();
                entity.DepartID = await GetDepId("purchase_permission");

                // dynamic dynamic = new ExpandoObject();
                (IEnumerable<dynamic>, int) SelectTable = await BusinessRule.Purchase.CGGL_CG.SelectCG_Invite(entity);


                Page pa = new Page();
                pa.records = SelectTable.Item1;
                pa.total = SelectTable.Item2;
                _logger.Log(LogLevel.Info, Success(pa).ToJson());
                return Success(pa);
            }
            catch (Exception)
            {
                return Fail("响应失败");
            }
        }


        //存草稿、提交

        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> SubmitCG_Bidder([FromBody] CG_Bidder_Sub zb)
        {

            try
            {
                if (zb.zbxx.zt == "" || zb.zbxx.zt == null)
                {
                    return Fail("数据状态错误");
                }
                if (zb.zbxx.bdid == "" || zb.zbxx.bdid == null)
                {
                    return Fail("请选择招标申请！");
                }
                if (zb.zbxx.bmdm == "" || zb.zbxx.bmdm == null)
                {
                    return Fail("数据权限缺失");
                }
                if (zb.zbxx.djbm == "" || zb.zbxx.djbm == null)
                {
                    zb.zbxx.djbm = await JavaApi.BusinessBMJavaAPI("purchase_bidder", "中标管理", await GetICApiInfo());
                    zb.zbxx.listid = "1";
                    //string listid = "1";
                }
                if (zb.zbxx.djbm == null)
                {
                    return Fail("单据编码获取失败");
                }
                if (zb.zbxx.zt == "1")
                {
                    if (await JavaApi.UploadFileJavaAPI(zb.zbxx.djbm, zb.File, await GetICApiInfo()))
                    {

                        await BusinessRule.Purchase.CGGL_CG.InsertCG_Bidder(zb);

                    }
                    else
                    {
                        await BusinessRule.Purchase.CGGL_CG.InsertCG_Bidder(zb);

                    }
                    return Success("成功");
                }
                else
                {

                    if (await JavaApi.UploadFileJavaAPI(zb.zbxx.djbm, zb.File, await GetICApiInfo()))
                    {
                        CG_Submit submit = new CG_Submit();
                        submit.submitid = zb.zbxx.djbm;
                        submit.submitmc = zb.zbxx.zbdw;
                        submit.submitje = zb.zbxx.zbje.ToString();
                        submit.submitlx = "中标录入";
                        bool bsp = false;
                        JavaApi.SPLEnt spl = new JavaApi.SPLEnt();
                        spl.businessName = "中标录入";
                        spl.businessId = zb.zbxx.djbm;
                        // spl.publicParamKey = "FEE_PROCESS";
                        spl.formCode = zb.File.code;

                        //spl.description = Newtonsoft.Json.JsonConvert.SerializeObject(htsmbmit);
                        JavaApi.SPLEnt.Auditdescription _description = new JavaApi.SPLEnt.Auditdescription() { businessNo = zb.zbxx.djbm, amount = zb.zbxx.zbje.ToString(), content = zb.zbxx.zbdw, deptName = zb.zbxx.tjr };
                        spl.description = _description.ToJson();
                        spl.additionInfoJson = Newtonsoft.Json.JsonConvert.SerializeObject(submit);
                        spl.callbackUrl = "http://ic-xmzc/netapi/CGManage/UpdateStatusCG_Bidder";
                        spl.callbackInterface = "";

                        //  spl.callbackInterface = "/contract-rule/collection/currency-audit/audit/${taskId}/" + ht.skhtxx.htbh + "/" + ht.skhtxx.htmc + "/" + ht.skhtxx.htlx + "/" + ht.skhtxx.zt + " ";


                        bsp = await JavaApi.startInstanceJavaAPI(spl, await GetICApiInfo());
                        if (bsp)
                        {
                            await BusinessRule.Purchase.CGGL_CG.InsertCG_Bidder(zb);
                            return Success("成功");
                        }
                        else
                        {
                            zb.zbxx.zt = "1";
                            await BusinessRule.Purchase.CGGL_CG.InsertCG_Bidder(zb);
                            return Fail("提交失败，启动工作流异常");
                        }
                    }

                    else
                    {
                        await BusinessRule.Purchase.CGGL_CG.InsertCG_Bidder(zb);

                    }
                    return Success("成功");

                }

            }

            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        //删除
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> DeleteCG_Bidder(List<string> djbm)
        {
            try
            {
                djbm.Add("autoid10000001");

                string strid = "";
                strid = string.Join("','", djbm.ToArray());

                if (!string.IsNullOrEmpty(strid))
                {
                    strid = "'" + strid + "'";
                }
                await BusinessRule.Purchase.CGGL_CG.DeleteCG_Bidder(strid);
                return Success("成功");
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        //审批回调
        [HttpPost]
        public async Task<IActionResult> UpdateStatusCG_Bidder(dynamic spjson)//
        {

            //module，dealUser，approveStatus，businessName，businessId
            try
            {
                _logger.Debug(JsonConvert.SerializeObject(spjson));

                string moduleid = spjson.module;
                string userid = spjson.dealUser;
                string approveStatus = spjson.approveStatus;//UNCHECK, CHECKING,REJECTED,INVALID,CHECKED

                //operation，值：AGREE（同意），REJECT（驳回），INVALID（作废），ACTIVATION（激活），CANCEL（撤销），RESTART（消审）
                string operation = spjson.operation;
                string businessId = spjson.businessId;
                string businessName = spjson.businessName;

                string additionInfo = spjson.additionInfo;
                if (string.IsNullOrEmpty(businessId))
                {
                    return Fail("业务id不能为空");
                }

                //待提交  未审核  审核中  作废  已审核  驳回
                //DRAFT  UNCHECK, CHECKING,INVALID,CHECKED
                string zt = "0";
                if (approveStatus == "DRAFT")
                {
                    zt = "1";
                }
                if (approveStatus == "UNCHECK")
                {
                    zt = "1";
                }
                if (approveStatus == "CHECKING")
                {
                    zt = "9";
                }
                if (approveStatus == "CHECKED")
                {
                    zt = "3";
                }
                if (approveStatus == "REJECT")
                {
                    zt = "4";
                }
                if (approveStatus == "INVALID")
                {
                    zt = "5";
                }
                if (approveStatus == "RESTART")
                {
                    zt = "1";
                }


                await BusinessRule.Purchase.CGGL_CG.UpdateCG_Bidderzt(businessId, zt);


                #region 加日志
                LogEntity logEntity = new LogEntity();
                logEntity.F_CategoryId = 3;
                logEntity.F_OperateTypeId = ((int)OperationType.Audit).ToString();
                logEntity.F_OperateType = EnumAttribute.GetDescription(OperationType.Audit);
                logEntity.F_OperateAccount = ContextHelper.GetItem("userName") as string;
                logEntity.F_OperateUserId = ContextHelper.GetItem("userId") as string;
                logEntity.F_Module = Request.Path;
                logEntity.F_IPAddress = Request.HttpContext.Connection.RemoteIpAddress.ToString();
                logEntity.F_ExecuteResult = -1;
                var timeConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };
                logEntity.F_ExecuteResultJson = JsonConvert.SerializeObject(spjson, timeConverter);
                //添加日志
                await LogRule.Write(logEntity);
                #endregion


                //return Success("操作成功");
                return Json(new ResParameter { code = ResponseCode.success, message = "成功" });
            }
            catch (Exception ex)
            {
                return Json(new ResParameter { code = ResponseCode.fail, message = "操作失败" + ex.Message });
                //return Fail("操作失败："+ ex.Message);
            }
        }
        #endregion
    }
}
